from django import template
from ..models import ScenicCategory

register = template.Library()

# === 表单相关过滤器 ===
@register.filter
def add_class(value, class_name):
    return value.as_widget(attrs={'class': class_name})

# === 分类相关标签 ===
@register.simple_tag
def get_scenic_categories():
    """获取景点分类"""
    return ScenicCategory.objects.filter(parent__isnull=True).prefetch_related('children')

@register.simple_tag
def get_natural_categories():
    """获取自然景观分类"""
    return ScenicCategory.objects.filter(category_type='natural', level=1, is_active=True)

@register.simple_tag
def get_cultural_categories():
    """获取人文历史分类"""
    return ScenicCategory.objects.filter(category_type='cultural', level=1, is_active=True)

# === 数学运算过滤器 ===
@register.filter
def get_item(dictionary, key):
    """从字典中获取值"""
    return dictionary.get(key)

@register.filter
def multiply(value, arg):
    """乘法过滤器"""
    try:
        return float(value) * float(arg)
    except (ValueError, TypeError):
        return 0

@register.filter
def divide(value, arg):
    """除法过滤器"""
    try:
        return float(value) / float(arg)
    except (ValueError, TypeError, ZeroDivisionError):
        return 0

@register.filter
def percentage(value, total):
    """计算百分比"""
    try:
        if total == 0:
            return 0
        return (float(value) / float(total)) * 100
    except (ValueError, TypeError):
        return 0

# === 文本处理过滤器 ===
@register.filter
def truncate_words_custom(value, arg):
    """自定义截断单词"""
    try:
        words = value.split()
        if len(words) <= arg:
            return value
        return ' '.join(words[:arg]) + '...'
    except AttributeError:
        return value

# === 数据统计过滤器 ===
@register.filter
def sum_attribute(queryset, attribute_name):
    """计算queryset中某个属性的总和"""
    try:
        return sum(getattr(item, attribute_name, 0) for item in queryset)
    except (TypeError, AttributeError):
        return 0

@register.filter
def avg_attribute(queryset, attribute_name):
    """计算queryset中某个属性的平均值"""
    try:
        items = list(queryset)
        if not items:
            return 0
        total = sum(getattr(item, attribute_name, 0) for item in items)
        return total / len(items)
    except (TypeError, AttributeError, ZeroDivisionError):
        return 0

@register.filter
def sum_heat_index(attractions):
    """计算热度指数总和"""
    try:
        return sum(attr.heat_index for attr in attractions)
    except (TypeError, AttributeError):
        return 0

@register.filter
def sum_review_count(attractions):
    """计算评论总数"""
    try:
        return sum(attr.review_count for attr in attractions)
    except (TypeError, AttributeError):
        return 0

@register.filter
def avg_heat_index(attractions):
    """计算平均热度指数"""
    try:
        if not attractions:
            return 0
        return sum(attr.heat_index for attr in attractions) / len(attractions)
    except (TypeError, AttributeError, ZeroDivisionError):
        return 0